package cn.qihua.action;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author 米修
 * 
 */
public class LoginAction extends ActionSupport {

	/**
	 * 登录
	 */
	private static final long serialVersionUID = 5456133835309901639L;

	public String username;
	public String password;
//	public String kaptcha;
	public Boolean rememberMe = false;
	public String message;

	@Override
	public String execute() throws Exception {
//		String captcha = (String) ActionContext.getContext().getSession()
//				.get(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//		System.out.println("captcha:"+captcha+"       Session  kaptcha:"+kaptcha);
//		if (captcha != null && kaptcha != null
//				&& !captcha.equalsIgnoreCase(kaptcha)) {
//			this.addActionError("验证码错误！");
//			return ERROR;
//		}
		if (username != null && password != null && !username.trim().equals("")
				&& !password.trim().equals("")) {
			UsernamePasswordToken token = new UsernamePasswordToken(username,
					password);
			token.setRememberMe(rememberMe);
			try {
				Subject subject = SecurityUtils.getSubject();
				subject.login(token);
				return SUCCESS;
			} catch (UnknownAccountException ex) {
				// username provided was not found
				this.addActionError("用户名不存在！");
				return ERROR;
			} catch (IncorrectCredentialsException ex) {
				// password provided did not match password found in database
				this.addActionError("密码错误！");
				return ERROR;
			} catch (Exception ex) {
				ex.printStackTrace();
				return ERROR;
			}

		} else {
			this.addActionError("用户名密码都不能为空！");
			return ERROR;
		}

	}

	/**
	 * 验证码SessionKey
	 */
	protected String getKaptchaSessionKey() {
		return com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;
	}

	public String getMessage() {
		return message;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Boolean getRememberMe() {
		return rememberMe;
	}

	public void setRememberMe(Boolean rememberMe) {
		this.rememberMe = rememberMe;
	}

}
